package models

import (
	"context"
	_ "time"

	orm "go-papers/database"
	"go-papers/pkg/lognew"
)

type OrderShare struct {
	OrderShareId int     `json:"orderShareId" gorm:"type:int(11);primary_key"` //
	OrderId      int     `json:"orderId" gorm:"type:int(11);"`                 //
	ShareName    string  `json:"shareName" gorm:"type:varchar(255);"`          // 分红人
	ShareStatus  string  `json:"shareStatus" gorm:"type:varchar(255);"`        // 分成状态 ：分成状态 1  待确认  5 已确认/已打款    10 待退回 20 已退回 50 取消关闭
	ShareDesc    string  `json:"shareDesc" gorm:"type:varchar(255);"`          // 描述
	ShareInfo    string  `json:"shareInfo" gorm:"type:varchar(255);"`          // 描述
	SharePrice   float64 `json:"sharePrice" gorm:"type:decimal(10,2);"`        // 分红金额
	ShareRate    float64 `json:"shareRate" gorm:"type:decimal(8,4);"`          // 分成比例
	ShareType    string  `json:"shareType" gorm:"type:varchar(255);"`          // 类型 1平台与机构 2 社区达人与拓展用户 3 社区达人与拓展机构
	ShareUserId  int     `json:"shareUserId" gorm:"type:int(11);"`             // 分红uid
	ShareTo      int     `json:"shareTo" gorm:"type:tinyint(2);"`              // 分红金额是否 退回 1 是， 0 否
	ShareTime    string  `json:"shareTime" gorm:"type:varchar(32);"`           // 分成时间

	ShareMomOrganPrice  float64 `json:"shareMomOrganPrice" gorm:"type:decimal(10,2);"`  //  签约机构达人佣金  shareMomOrganPrice
	ShareMomOrganRate   float64 `json:"shareMomOrganRate" gorm:"type:decimal(8,4);"`    //  签约机构达人佣金占比 shareMomOrganRate
	ShareMomMemberPrice float64 `json:"shareMomMemberPrice" gorm:"type:decimal(10,2);"` //  拓展用户达人佣金 shareMomMemberPrice
	ShareMomMemberRate  float64 `json:"shareMomMemberRate" gorm:"type:decimal(8,4);"`   //  拓展用户达人佣金占比  shareMomMemberRate
	ShareOrganPrice     float64 `json:"shareOrganPrice" gorm:"type:decimal(10,2);"`     //  机构课程费用   shareOrganPrice
	ShareOrganRate      float64 `json:"shareOrganRate" gorm:"type:decimal(8,4);"`       //  机构课程费用占比 shareOrganRate

	ShareMomLevel string `json:"shareMomLevel" gorm:"type:varchar(255);"` //  拓展用户达人 当前的分佣金 等级level

	DataScope string `json:"dataScope" gorm:"-"`
	Params    string `json:"params"  gorm:"-"`
	BaseModel
}

func (OrderShare) TableName() string {
	return "order_share"
}

// 创建OrderShare
func (e *OrderShare) Create() (OrderShare, error) {
	var doc OrderShare
	result := orm.Eloquent.Table(e.TableName()).Create(&e)
	if result.Error != nil {
		err := result.Error
		return doc, err
	}
	doc = *e

	if doc.ShareType == "2" || doc.ShareType == "3" {
		mid := doc.ShareUserId
		//获取 社区达人的佣金
		if doc.SharePrice > 0 {
			price := doc.SharePrice
			if doc.ShareStatus == "10" { // 退回
				price = -doc.SharePrice
			}
			//2.更新达人 佣金 与客户数量
			var mom MemberMom
			mom.MemberId = mid
			momInfo, err := mom.Get()
			if err != nil {
				mom.MemberId = mid
				mom.MomLevel = "0"
				mom.MomNewer = 0
				mom.MomOrgan = 0
				mom.MomCommission += price
				if mom.MomCommission <= 0 {
					mom.MomCommission = 0
				}
				_, err = mom.Create()
				if err != nil {
					lognew.Error(context.TODO(), "MomInfoInsert", lognew.Fields{"doc": doc, "err": err.Error()})
				}
			} else {
				momInfo.MomCommission += price
				if mom.MomCommission <= 0 {
					mom.MomCommission = 0
				}
				_, err = momInfo.Update(momInfo.MemberMomId)
				if err != nil {
					lognew.Error(context.TODO(), "MomInfoUpdate", lognew.Fields{"doc": doc, "err": err.Error()})
				}
			}
		}
	}
	return doc, nil
}

func (e *OrderShare) GetListV2() []OrderShare {
	var doc []OrderShare
	table := orm.Eloquent.Select("*").Table(e.TableName())

	if e.OrderId <= 0 {
		e.OrderId = -1
	}
	table = table.Where("order_id = ?", e.OrderId)
	table = table.Where("share_price > 0 ")
	table = table.Where("share_type in (2, 3)")
	if e.ShareStatus != "" {
		table = table.Where("share_status = ?", e.ShareStatus)
	}
	if e.ShareName != "" {
		table = table.Where("share_name like ?", "%"+e.ShareName+"%")
	}
	if err := table.Find(&doc).Error; err != nil {
		return nil
	}
	return doc
}

// 获取OrderPay
func (e *OrderShare) GetList() []OrderShare {
	var doc []OrderShare
	table := orm.Eloquent.Select("*").Table(e.TableName())

	if e.OrderId <= 0 {
		e.OrderId = -1
	}
	table = table.Where("order_id = ?", e.OrderId)
	table = table.Where("share_price > 0 ")
	if e.ShareType != "" {
		table = table.Where("share_type = ?", e.ShareType)
	}
	if e.ShareStatus != "" {
		table = table.Where("share_status = ?", e.ShareStatus)
	}
	if e.ShareName != "" {
		table = table.Where("share_name like ?", "%"+e.ShareName+"%")
	}
	if err := table.Find(&doc).Error; err != nil {
		return nil
	}
	return doc
}

// GetOne

// GetFirst
func (e *OrderShare) GetFirst(oid int) (OrderShare, error) {
	var doc OrderShare
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("order_id = ?", oid)
	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

// 获取OrderShare
func (e *OrderShare) Get() (OrderShare, error) {
	var doc OrderShare
	table := orm.Eloquent.Table(e.TableName())

	if e.OrderId != 0 {
		table = table.Where("order_id = ?", e.OrderId)
	}
	if e.ShareType != "" {
		table = table.Where("share_type = ?", e.ShareType)
	}
	if e.ShareUserId != 0 {
		table = table.Where("share_user_id = ?", e.ShareUserId)
	}
	if e.ShareTime != "" {
		table = table.Where("share_time = ?", e.ShareTime)
	}

	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

// 获取OrderShare带分页
func (e *OrderShare) GetPage(pageSize int, pageIndex int) ([]OrderShare, int, error) {
	var doc []OrderShare

	table := orm.Eloquent.Select("*").Table(e.TableName())
	if e.OrderId != 0 {
		table = table.Where("order_id = ?", e.OrderId)
	}

	var count int

	if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("`deleted_at` IS NULL").Count(&count)
	return doc, count, nil
}

// 更新OrderShare
func (e *OrderShare) Update(id int) (update OrderShare, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("order_share_id = ?", id).First(&update).Error; err != nil {
		return
	}

	//参数1:是要修改的数据
	//参数2:是修改的数据
	if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
		return
	}
	return
}

// 删除OrderShare
func (e *OrderShare) Delete(id int) (success bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("order_share_id = ?", id).Delete(&OrderShare{}).Error; err != nil {
		success = false
		return
	}
	success = true
	return
}

//批量删除
func (e *OrderShare) BatchDelete(id []int) (Result bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("order_share_id in (?)", id).Delete(&OrderShare{}).Error; err != nil {
		return
	}
	Result = true
	return
}
